import { useImperativeHandle } from 'react';
import { Modal, Form, Input } from 'antd';
import { useForm } from 'antd/es/form/Form';
import TextArea from 'antd/es/input/TextArea';
import { useState } from 'react';
import { IAction, IModalProps } from '@/types/modal';
import { Role } from '@/types';
import { createRole, editRole } from '@/api';
import { message } from '@/utils/AntdGlobal';

export default function CreateRole(props: IModalProps<Role.RoleItem>) {
  const [visiable, setVisiable] = useState(false);
  const [action, setAction] = useState<IAction>('create');
  const [form] = useForm();
  const handleSubmit = async () => {
    const valid = await form.validateFields();
    if (valid) {
      if (action === 'create') {
        await createRole(form.getFieldsValue());
        message.success('创建成功');
        form.resetFields();
      }
      if (action === 'edit') {
        await editRole(form.getFieldsValue());
        message.success('编辑成功');
      }
      props.update();
      setVisiable(false);
    }
  };
  const handleCancel = () => {
    setVisiable(false);
  };
  useImperativeHandle(props.mRef, () => ({
    open
  }));
  const open = (type: IAction, data?: Role.RoleItem) => {
    setAction(type);
    setVisiable(true);
    if (data) {
      form.setFieldsValue(data);
    }
  };
  return (
    <Modal
      title={action === 'create' ? '新增角色' : '编辑角色'}
      width={800}
      open={visiable}
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form labelCol={{ span: 4 }} labelAlign='right' form={form}>
        <Form.Item name='_id' hidden>
          <Input></Input>
        </Form.Item>
        <Form.Item
          label='角色名称'
          name='roleName'
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input placeholder='请输入角色名称'></Input>
        </Form.Item>
        <Form.Item label='备注' name='remark'>
          <TextArea placeholder='请输入备注'></TextArea>
        </Form.Item>
      </Form>
    </Modal>
  );
}
